import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:async';
import 'package:toast/toast.dart';
import 'device_name.dart';
import 'blueUuid.dart';
import 'package:flutter/foundation.dart';

class WeightControllerPage extends StatefulWidget {

  @override
  State<StatefulWidget> createState() =>_WeightPageState();
}

class _WeightPageState extends State<WeightControllerPage> {
  static const platform = const MethodChannel('my.flutter.io/bluetooth'); //定义与底层操作系统的方法调用通道
  static const EventChannel _eventChannelPlugin = EventChannel('my.flutter.event/bluetooth'); //定义接收底层操作系统主动发来的消息通道
  StreamSubscription _streamSubscription; //广播流来处理EventChannel发来的消息

  String _floatButtonText='开始';
  bool _currentState=false;//false表示当前没有开始获取体重
  int _currentWeightInt=0;//体重的整数部分
  int _currentWeightFloat=0;//体重的小数部分

  //widget初始化之后调用
  void afterBuildCallback(BuildContext context) {

  }

  @override
  void initState() {
    //当Widget第一次插入到Widget树时会被调用,并且只会调用一次
    super.initState();
    _streamSubscription = _eventChannelPlugin
        .receiveBroadcastStream()
        .listen(_onToDart, onError: _onToDartError); //注册消息回调函数
    WidgetsBinding.instance.addPostFrameCallback((_) =>
        afterBuildCallback(context)); //注册一个回调函数在widget初始化完成之后调用
  }

  void _onToDart(dynamic message) {
    //底层发送成功消息时会进入到这个函数来接收
    if(message["deviceName"]==DeviceName.WEIGHT_DEVICE_NAME){//如果是发给自己的才去处理
      switch(message['code']){
        case '80005'://如果是notify传回来的数据
          Uint8List data=message['data'];
          if(data[1]==0xD1){//如果是体重数据返回
            setState(() {
              _currentWeightInt=data[3];
              _currentWeightFloat=data[4];
            });
          }
          break;
        case "80002"://如果连接被手动断开
          Navigator.popUntil(context, ModalRoute.withName('home'));//就直接回到主界面
          break;
      }
    }
  }

  void _onToDartError(dynamic error) {
    //底层发送错误消息时会进入到这个函数来接收
    if(error.details==DeviceName.WEIGHT_DEVICE_NAME){//如果是发给自己的才去处理
      switch(error.code){
        case "90001"://如果扫描不到目标设备
          Navigator.popUntil(context, ModalRoute.withName('home'));//就直接回到主界面
          break;
        case "90002"://与设备的连接断开
          _showToast('与设备的连接断开,现在尝试再去连接设备');
          Map<String,Object> dataMap={
            "deviceName":DeviceName.WEIGHT_DEVICE_NAME,
            "uuidDataType":defaultTargetPlatform==TargetPlatform.android?BlueUuid.androidWeightUuidType:null,
            "deviceUuid":defaultTargetPlatform==TargetPlatform.android?BlueUuid.androidWeightUuid:BlueUuid.iosWeightUuid,
            "notify_d":defaultTargetPlatform==TargetPlatform.android?BlueUuid.androidNotify_d:null,
            "notifyUuid":defaultTargetPlatform==TargetPlatform.android?BlueUuid.androidWeightNotifyUuid:BlueUuid.iosWeightNotifyUuid
          };
          platform.invokeMethod('connectDevice',dataMap).then((value) {});//调用底层去连接蓝牙设备
          break;
      }
    }
  }
  @override
  Widget build(BuildContext context) {
    return new WillPopScope(
        onWillPop: () async {
          //导航回到主界面
          platform.invokeMethod('disConnectDevice', DeviceName.WEIGHT_DEVICE_NAME).then((
              value) {}); //调用底层去与蓝牙设备断开连接
          return false;
        },
        child: Scaffold(
            appBar: AppBar(
              title: Text("体重称"),
            ),
            body: Center(
                child: Text('当前体重：' +
                    (_currentState ? _currentWeightInt.toString() + '.' +
                        _currentWeightFloat.toString() : '') + '(KG)',
                    style: TextStyle(fontSize: 18)
                )
            ),
            floatingActionButton: new FloatingActionButton(
              onPressed: () {
                Uint8List data = new Uint8List(4);
                data[0] = 0xFE;
                data[1] = 0xDC;
                data[2] = 0x01;
                data[3] = _currentState ? 0x00 : 0x01;
                setState(() {
                  _currentState = !_currentState; //停止获取体重则不显示体重数值
                  _floatButtonText = _currentState ? '停止' : '开始';
                });
                Map<String, Object> dataMap = {"data": data};
                _callPlatformToSendData(dataMap); //调用底层去向蓝牙设备发送消息
              },
              tooltip: _floatButtonText,
              child: Text(_floatButtonText),
            )
        )
    );
  }

  //显示toast
  void _showToast(String text){
    Toast.show(text, context, duration: Toast.LENGTH_SHORT, gravity:  Toast.BOTTOM);
  }

  //向底层操作系统发送消息去给蓝牙设备
  void _callPlatformToSendData(Map<String,Object> dataMap){
    dataMap["deviceName"]=DeviceName.WEIGHT_DEVICE_NAME;
    dataMap["serviceUuid"]=defaultTargetPlatform==TargetPlatform.android?BlueUuid.androidWeightServiceUuid:BlueUuid.iosWeightServiceUuid;
    dataMap["writeUuid"]=defaultTargetPlatform==TargetPlatform.android?BlueUuid.androidWeightWriteUuid:BlueUuid.iosWeightWriteUuid;
    dataMap["notifyUuid"]=defaultTargetPlatform==TargetPlatform.android?BlueUuid.androidWeightNotifyUuid:BlueUuid.iosWeightNotifyUuid;
    dataMap["isWithResult"]=true;
    platform.invokeMethod('sendData',dataMap).then((result){});//调用底层去向蓝牙设备发送消息
  }
}